
import plugin
import card
from game import Hall, DISCARD_COMMAND

class OUATHall(Hall):
    def __init__(self, admin, profile,conf,conn, reactor, users=[]):
        users = users[:]
        users.append(admin)
        Hall.__init__(self,profile,conf,conn,reactor,users)
        self.__admin = admin
        self.__game_flag = False
        plugin.command_plugin.Cmd_Roll().PlugIn(self)

    def start(self):
        self.__story_cards = card.get_story_cards()
        self.__endding_cards = card.get_endding_card()
        self.__users = {}
        story_card_count = 5
        if len(self.user_list) == 1:
            self.systoall("we have not enough people to start the game.")
            return
        elif len(self.user_list) == 2:
            story_card_count = 10
        elif 2 < len(self.user_list) < 6:
            story_card_count = 11 - len(self.user_list)

        for user in self.user_list:
            self.__users[user] = {
                "Endding":self.__endding_cards.get_random()[0],
                "Story": self.__story_cards.get_random(story_card_count)}
            self.__users[user]['Story'].sort(card.story_card_cmp)
        self.__game_flag = True
        self.systoall("Game Start.")
        self.systoall("Once Upon A Time...")

    def startHandler(self,who,msg):
        '"/start" Start a new game. Only admin can use it.'
        if self.getindexname(who) != self.__admin:
            self.systoone(who, "You aren't admin!")
        else:
            if self.__game_flag:
                self.systoone(who,"The game started.")
            else:
                self.start()
        pass

    def encode_endding_card(self,card):
        return u"No:%(no)d %(chinese)s"%card

    def encode_story_card(self,card):
        return "  ".join([y for x,y in card.items()])

    def deal(self, user, count = 1):
        try:
            cards = self.__story_cards.get_random(count)
        except card.NO_ENOUGH_CARD:
            self.systoall("NO ENOUGH CARDS FOR %s TO DRAW!!!"%user)
            return
        self.systoone(user,"Your got the Cards:\r\n%s\r\n"%\
            "\r\n".join([self.encode_story_card(x) for x in cards]))
        self.systoall("%s got %d card(s)"%(user,count))
        self.__users[user]['Story'].extend(cards)
        self.__users[user]['Story'].sort(card.story_card_cmp)

    def dealHandler(self,who,msg):
        '"/deal [number]" deal one or more cards to you.'
        if not self.__game_flag:
            self.systoone(who,"The game is not started.")
            return
        if msg =="":
            self.deal(self.getindexname(who))
        else:
            try:
                count = int(msg.strip()[0])
            except:
                self.systoone(who, "Usage: /deal [number]")
                return
            self.deal(self.getindexname(who), count)
        pass

    def putHandler(self,who,msg):
        '"/put card_name" put a card out.'
        if not self.__game_flag:
            self.systoone(who,"The game is not started.")
            return
        user = self.getindexname(who)
        if msg == "":
            self.systoone(who, "Usage: /put card_name")
            return
        msg = msg.strip()
        if msg == "end":
            if len(self.__users[user]["Story"]):
                self.systoone(who,"you still have some story card!")
            elif self.__users[user]["Endding"]:
                self.systoall("WOW! %s put the ENDDING card (%s) out"%(user, self.__users[user]["Endding"]['chinese']))
                self.__users[user]["Endding"]=NONE
            else:
                self.systoone(who,"You has no endding card!")
            return
        else:
            for card in self.__users[user]['Story']:
                if card['name'].lower() == msg.lower() or card["chinese"] == msg:
                    self.systoall("%s put the STORY card (%s) out"%(user, self.encode_story_card(card)))
                    self.__users[user]['Story'].remove(card)
                    return       
            self.systoone(who,"You hasn't this card") 
        pass

    def show_user_his_card(self,user):
        self.systoone(user,"Your Story Cards:\r\n%s\r\n"%\
            "\r\n".join([self.encode_story_card(x) for x in self.__users[user]['Story']]))
        if self.__users[user]['Endding']:
            self.systoone(user,"Your Endding Card:\r\n%s"%self.encode_endding_card(self.__users[user]['Endding']))

    def listHandler(self,who,msg):
        '"/list" list the card you have.'
        if not self.__game_flag:
            self.systoone(who,"The game is not started.")
            return
        user = self.getindexname(who)
        self.show_user_his_card(user)
        pass
    def endHandler(self,who,msg):
        '"/end" End this game. Only admin can use it.'
        if self.getindexname(who) != self.__admin:
            self.systoone(who, "You aren't admin!")
        else:
            self.systoall("The End!")
            raise DISCARD_COMMAND
        pass
    def resetHandler(self,who,msg):
        '"/reset" Reset this game. Only admin can use it.'
        if self.getindexname(who) != self.__admin:
            self.systoone(who, "You aren't admin!")
        else:
            self.systoall("The OUAT Reloaded!")
            self.start()
        pass
